package com.ruiysoft.crm.util;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author fanyl5
 */
@Slf4j
public class ExcelListener<T> extends AnalysisEventListener<T> {


    @Getter
    @Setter
    private List<T> dataList = Lists.newArrayList();
    private static final String SERIAL_VERSION_UID = "serialVersionUID";

    @Override
    public void invoke(T object, AnalysisContext context) {
        log.info("解析到一条数据：{}", JSON.toJSONString(object));
        if (!checkObjAllFieldsIsNull(object)) {
            dataList.add(object);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成，数据量是{}", dataList.size());
        //dataList.clear();
    }


    /**
     * 判断对象中属性值是否全为空
     */
    private static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }

        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                //只校验带ExcelProperty注解的属性
                ExcelProperty property = f.getAnnotation(ExcelProperty.class);
                if (property == null || SERIAL_VERSION_UID.equals(f.getName())) {
                    continue;
                }
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            //do something
        }
        return true;
    }
}
